﻿using AutoMapper;
using H2.NET.Business.Core;
using H2.NET.Common;
using H2.NET.Web.Workflow.Models;
using H2.NET.Web.Workflow.Services;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using Ultimus.OC;

namespace H2.NET.Web.Index
{
    /// <summary>
    /// 注：“快捷菜单”需要有 Channel All 工作组、与菜单配置权限之后才能正常显示
    /// </summary>
    public partial class Menu : UserControl
    {
        [SessionType]
        public clsCommon clsCmm = new clsCommon();
        public string SessionUser = HttpContext.Current.Session["SessionUser"] as String;

        public DataTable dt = new DataTable();
        public DataTable reports = new DataTable();
        public DataTable MyReports = new DataTable();

        

        #region 事件 页面 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            MenuBind();
        }
        #endregion

        public void MenuBind()
        {
            try
            {
                AccountService accountService = new AccountService();
                RoleService roleService = new RoleService();
                GroupService groupService = new GroupService();
                PermissionService permissionService = new PermissionService();

                OrgChart oc = new OrgChart();
                User ocUser = new User();
                oc.FindUser(Page.User.Identity.Name, "", 0, out ocUser);
                if (ocUser == null)
                {
                    Response.Redirect("~/SystemError.aspx?ex=对不起，系统（OrgChart）中没有该用户（" + Page.User.Identity.Name + "）");
                    return;
                }

                var username = Util.AppSettings("debug").Trim().ToUpper() == "YES"
                    ? clsCmm.comm_username
                    : Page.User.Identity.Name;

                t_mdc_Account account = accountService.GetAccount(username) ?? accountService.GetAccount("*");

                var dt_roles = roleService.FindRoleByAccountId(account.Id);
                var rows = dt_roles.Select("name = '超级管理员'");
                if (rows.Count() > 0)
                {
                    clsCmm.comm_is_administrator = true;
                }
                else
                {
                    clsCmm.comm_is_administrator = false;
                }

                UserSession us = new UserSession
                {
                    SessionId = Session.SessionID,
                    LastLoginTime = account.LastLoginTime,
                    Name = account.Username,
                    UserId = account.Id,
                    Permissions = new List<Permission>()
                };

                var permissions = permissionService.GetByUserId(us.UserId);

                var isChannelAll = groupService.IsChannelAll(username);
                if (!isChannelAll)
                {
                    permissions = permissions.Where(t => t.Name != "快捷菜单").ToList();
                }
                foreach (var perm in permissions)
                {
                    var model = Mapper.Map<t_mdc_Permission, Permission>(perm);
                    if (us.Permissions.Select(t => t.ID).Contains(perm.Id)) continue;
                    us.Permissions.Add(model);
                }

                Session["UserSession"] = us;
                string strSQL;

                #region 左菜单数据取得
                //主查询 SQL
                strSQL = "select rtrim(p.id) as id";
                strSQL += "       ,rtrim(p.parentid) as parent_id";
                strSQL += "       ,p.name";
                strSQL += "       ,p.[url] as url";
                strSQL += "       ,p.layer";
                strSQL += "       ,p.[order] as seque";
                strSQL += "       ,1 as types";
                strSQL += "       ,p.OpenMode";
                strSQL += "       ,p.RelCode";
                strSQL += "  from t_mdc_Permission p";
                strSQL += "  inner join t_mdc_PermissionRole pr on p.id = pr.Permission_Id";
                strSQL += "  inner join t_mdc_Role r on r.id = pr.Role_Id";
                strSQL += "  inner join t_mdc_RoleAccount ra on ra.Role_Id = r.id";
                strSQL += "  inner join t_mdc_Account a on a.id = ra.Account_Id";
                strSQL += "  where a.Username = '" + us.Name + "'";
                if (!isChannelAll)
                {
                    strSQL += " and p.name != '快捷菜单'";
                }

                strSQL += "  union";

                //报表菜单取得
                strSQL += " select cfg_no as id ";
                strSQL += "       ,cfg_p_menu_id as parent_id";
                if (clsCmm.comm_language == "en-us")
                {
                    strSQL += "       ,cfg_name_en as name";
                }
                else
                {
                    strSQL += "       ,cfg_name_cn as name";
                }
                strSQL += "       ,cfg_no as url";
                strSQL += "       ,2 as layer";
                strSQL += "       ,cfg_sequence as seque";
                strSQL += "       ,2 as types";
                strSQL += "       ,'iframe' as OpenMode";
                strSQL += "       ,cfg_name_en as RelCode";
                strSQL += "   from t_report";
                strSQL += "  where cfg_no in(";
                strSQL += " select cfg_g_fk_cfg_no";
                strSQL += "   from t_report_group";
                strSQL += "  where cfg_g_grp_no in(";
                strSQL += " select distinct a.grp_m_fk_grp_no";
                strSQL += "   from t_group_member a";

                //如果是管理员的情况，则显示所有报表
                if (!clsCmm.comm_is_administrator)
                {
                    strSQL += "  where a.grp_m_type_v in ('[current_dept]', '[all_dept]', '[current_user]','[all_user]', '[current_job]', '[all_job]')";
                    strSQL += "     or (a.grp_m_type='1' and a.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_dept}") + "'))";
                    strSQL += "     or (a.grp_m_type='2' and a.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_user}") + "'))";
                    strSQL += "     or (a.grp_m_type='3' and a.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_job}") + "'))";
                }
                strSQL += "                       )";
                strSQL += "                  )";

                strSQL += "  union";

                //报表菜单取得
                strSQL += " select cfg_no as id ";
                strSQL += "       ,cfg_p_menu_id as parent_id";
                if (clsCmm.comm_language == "en-us")
                {
                    strSQL += "       ,cfg_name_en as name";
                }
                else
                {
                    strSQL += "       ,cfg_name_cn as name";
                }
                strSQL += "       ,cfg_no as url";
                strSQL += "       ,2 as layer";
                strSQL += "       ,cfg_sequence as seque";
                strSQL += "       ,3 as types";
                strSQL += "       ,'iframe' as OpenMode";
                strSQL += "       ,cfg_name_en as RelCode";
                strSQL += "   from t_data";
                strSQL += "  where cfg_no in(";
                strSQL += " select cfg_g_fk_cfg_no";
                strSQL += "   from t_data_group";
                strSQL += "  where cfg_g_grp_no in(";
                strSQL += " select distinct b.grp_m_fk_grp_no";
                strSQL += "   from t_group_member b";

                //如果是管理员的情况，则显示所有报表
                if (!clsCmm.comm_is_administrator)
                {
                    strSQL += "  where b.grp_m_type_v in ('[current_dept]', '[all_dept]', '[current_user]','[all_user]', '[current_job]', '[all_job]')";
                    strSQL += "     or (b.grp_m_type='1' and b.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_dept}") + "'))";
                    strSQL += "     or (b.grp_m_type='2' and b.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_user}") + "'))";
                    strSQL += "     or (b.grp_m_type='3' and b.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_job}") + "'))";
                }
                strSQL += "                       )";
                strSQL += "                  )";
                strSQL += " order by seque";

                clsCmm.clsDB.Storage("oleDB");
                dt = clsCmm.clsDB.Query(strSQL);
                #endregion

                #region 判断一级菜单是否存在下层的二级菜单、如果不存在则移除
                //判断并移除不存在二级菜单的一级菜单情况
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //如果是报表的情况，加上页面链接
                    if (dt.Rows[i]["types"].ToString() == "2")
                    {
                        dt.Rows[i]["url"] = "reports/rpt_run_report.aspx?no=" + dt.Rows[i]["url"].ToString();
                    }

                    if (dt.Rows[i]["types"].ToString() == "3")
                    {
                        dt.Rows[i]["url"] = "reports/rpt_run_data.aspx?no=" + dt.Rows[i]["url"].ToString();
                    }

                    //如果是二级期间则执行下一轮循环
                    if (dt.Rows[i]["layer"].ToString() == "2")
                    {
                        continue;
                    }

                    //如果是一级菜单的情况
                    bool Flg = true;
                    if (dt.Rows[i]["layer"].ToString() == "1")
                    {
                        //判断是否存在二级菜单
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            if (i == j || dt.Rows[j]["layer"].ToString() == "1")
                            {
                                continue;
                            }

                            if (dt.Rows[i]["id"].ToString() == dt.Rows[j]["parent_id"].ToString())
                            {
                                Flg = false;
                                break;
                            }
                        }
                    }

                    //如果不存在二级菜单则删除当前菜单
                    //if (Flg)
                    //{
                    //    dt.Rows.RemoveAt(i);
                    //    dt.AcceptChanges();
                    //    i--;
                    //}
                }
                DataTable dt1 = new DataTable();
                clsCmm.clsDB.Storage("smdDB");
                dt1 = clsCmm.clsDB.Query("select configid,name,code from t_smd_Config where Parentid is null");
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    if (dt1.Rows[i]["code"].ToString().Contains("M_"))
                    {
                        DataRow dr = dt.NewRow();
                        dr["id"] = 33;
                        dr["parent_id"] = 44;
                        dr["name"] = dt1.Rows[i]["name"].ToString();
                        dr["url"] = "/Management/Config/IndexMany.aspx?pId=" + dt1.Rows[i]["configid"].ToString();
                        dr["layer"] = 2;
                        dr["RelCode"] = "ConfigIndex_" + dt1.Rows[i]["configid"].ToString();
                        dt.Rows.Add(dr);
                    }
                    else
                    {
                        DataRow dr = dt.NewRow();
                        dr["id"] = 33;
                        dr["parent_id"] = 44;
                        dr["name"] = dt1.Rows[i]["name"].ToString();
                        dr["url"] = "/Management/Config/Index.aspx?pId=" + dt1.Rows[i]["configid"].ToString();
                        dr["layer"] = 2;
                        dr["RelCode"] = "ConfigIndex_" + dt1.Rows[i]["configid"].ToString();
                        dt.Rows.Add(dr);
                    }
                }

                #endregion

                #region 加上id参数，为了获取按钮权限

                foreach (DataRow row in dt.Rows)
                {
                    string url = row["url"].ToString();
                    string id = row["id"].ToString();

                    row["url"] = url + (url.Contains("?") ? "&" : "?") + "mid=" + id;
                }

                #endregion

                #region 读取报表
                string msql = "select t.id,t.name,t.create_user from bi_Template t ";
                string rsql = "select t.id,t.name,t.create_user from bi_Template t ";
                string nsql = " select b.grp_m_fk_grp_no as groupNo";
                nsql += "  from t_group_member b";
                nsql += " where b.status = 1 and b.grp_m_type_v = '" + clsCmm.comm_username + "'";
                nsql += " order by b.grp_m_type";
                clsCmm.clsDB.Storage("oleDB");
                DataTable ndt = clsCmm.clsDB.Query(nsql);
                string nos = "(";
                foreach (DataRow n in ndt.Rows)
                {
                    if (n.ItemArray.Length > 0)
                    {
                        nos += "'" + n.ItemArray[0].ToString() + ",',";
                    }
                }
                if (nos.LastIndexOf(",")>=0)
                {
                    nos = nos.Substring(0, nos.Length - 1);
                }
                nos += ")";
                msql += " where create_user = '" + clsCmm.comm_username + "'";
                rsql += " where create_user <> '" + clsCmm.comm_username + "'";
                if (!clsCmm.comm_is_administrator)
                {
                    rsql += " and permission in " + nos;
                }
                reports = clsCmm.clsDB.Query(rsql);
                MyReports = clsCmm.clsDB.Query(msql);
                #endregion

            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 index_menu.ascx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
    }
}
